module Auditing
  def self.append_features(base)
    base.after_create do |object|
      Auditing::insert_delete_audit_entry("insert", object)
    end
    base.after_update do |object|
      Auditing::update_audit_entry("update", object)
    end
    base.after_destroy do |object|
      Auditing::insert_delete_audit_entry("delete", object)
    end
  end
  def self.insert_delete_audit_entry(operation, object)
    unless object.kind_of?(Mudanca) || object.kind_of?(Audit)
      Audit.create(:operacao => operation,
        :model => object.class.name,
        :objeto_id => object.id,
        :user_id => User.current_user_id,
        :created_at => DateTime.now)
    end
  end

  def self.update_audit_entry(operation, object)
    unless object.kind_of?(Mudanca) || object.kind_of?(Audit)

      audit = Audit.new
      audit.operacao = operation
      audit.model = object.class.name
      audit.objeto_id = object.id
      audit.user_id = User.current_user_id
      audit.created_at = DateTime.now
      audit.save

      if object.changed.include?("updated_at")
        mudancas = object.changed
        mudancas.delete("updated_at")
        mudancas.each do |ch|
          Mudanca.create(
            :campo => ch,
            :antes => object.changes[ch][0],
            :depois => object.changes[ch][1],
            :audit_id => audit.id
          )
        end
      else
        object.changed.each do |ch|
          Mudanca.create(
            :campo => ch,
            :antes => object.changes[ch][0],
            :depois => object.changes[ch][1],
            :audit_id => audit.id
          )
        end
      end
    end
  end

  #ActiveRecord::Base.class_eval do
  #  include Auditing
  #end
end